package com.zxb.core.common.validation;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * @author Zxb
 */
@Documented
@Constraint(validatedBy = {Mobile.Validator.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Mobile {

    String message() default "不符合手机号码格式";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class Validator implements ConstraintValidator<Mobile, String> {
        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            if (StrUtil.isEmpty(value)) {
                return true;
            }
            return PhoneUtil.isMobile(value);
        }
    }
}
